﻿using MediatR;
using AutoMapper;
using System.Linq.Expressions;
using Management.API.Application.Controller.Management;
using Management.API.DTOs.Management;
using Management.Domain;
using Management.Errorcode;
using Management.Errorcode.ErrorCode;
using Management.Infrastructure.Interfaces;
using Management.Infrastructure.Interfaces.BOMManagement;
using Management.Models.BOMBasicInformation;
using Management.API.Utils;
using MySqlX.XDevAPI.Common;
using System.Collections.Immutable;
using Management.API.Application.CommandHandler.Management.BasicInformation;


namespace Management.API.Application.CommandHandler.Management
{
    public class GetIDBasicInformationCommandHandler : IRequestHandler<GetBasicInformationCommand, ApiResult<PagingResult<IList<GetBasicInformationDTO>>>>
    {
        private readonly IBasicInformationRepository _iBasicInformationRepository;
        private readonly IMaterialRepository _iMaterialRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetIDBasicInformationCommandHandler> _logger;

        public GetIDBasicInformationCommandHandler(IBasicInformationRepository IBasicInformationRepository,
            IMaterialRepository IMaterialRepository, IMapper mapper, ILogger<GetIDBasicInformationCommandHandler> logger)
        {
            _iBasicInformationRepository = IBasicInformationRepository;
            _iMaterialRepository = IMaterialRepository;
            _mapper = mapper;
            _logger = logger;
        }


        //async Task<ApiResult<PagingResult<IList<GetBasicInformationDTO>>>> IRequestHandler<GetBasicInformationCommand, ApiResult<PagingResult<IList<GetBasicInformationDTO>>>>.Handle(GetBasicInformationCommand request, CancellationToken cancellationToken)
        //{
        //    try
        //    {
        //        //
        //        var BasicInformations = await _iBasicInformationRepository.GetAllAsync();
        //        var Materials = await _iMaterialRepository.GetAllAsync();

        //        // 外健链接
        //        var result = from BasicInformation in BasicInformations
        //                     join Material in Materials on BasicInformation.MaterialTypeId equals Material.MaterialId
        //                     select new GetBasicInformationDTO
        //                     {
        //                         BomNumber = BasicInformation.BomNumber,
        //                         BomNumberingState = BasicInformation.BomNumberingState,
        //                         BomVersionNumber = BasicInformation.BomVersionNumber,
        //                         BomSpecificationModel = BasicInformation.BomSpecificationModel,
        //                         BomDefault = BasicInformation.BomDefault,
        //                         BomDailyOutput = BasicInformation.BomDailyOutput,
        //                         BomRemark = BasicInformation.BomRemark,
        //                         BomUsageAmount = BasicInformation.BomUsageAmount,
        //                         BomRatioMaterialsUsed = BasicInformation.BomRatioMaterialsUsed,
        //                         BomNameProcessRoute = BasicInformation.BomNameProcessRoute,
        //                         BomProcessNumber = BasicInformation.BomProcessNumber,
        //                         BomProcessSpecification = BasicInformation.BomProcessSpecification,
        //                         UnitName = BasicInformation.UnitName,
        //                         UnitId = BasicInformation.UnitId,
        //                         MaterialTypeId = BasicInformation.MaterialTypeId,
        //                         ProductTypeId = BasicInformation.ProductTypeId,
        //                     };

        //        // 当前页的数据
        //        var currentData = _mapper.Map<IList<GetBasicInformationDTO>>(result.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize).ToList());

        //        // 分页
        //        var pagingResult = new PagingResult<IList<GetBasicInformationDTO>>
        //        {
        //            TotalCount = result.Count(),
        //            TotalPage = Math.Ceiling(result.Count() / (double)request.PageSize),
        //            Data = currentData
        //        };

        //        // 返回成功结果
        //        return ApiResult<PagingResult<IList<GetBasicInformationDTO>>>.Success(pagingResult, StatusCodeEnum.Success);
        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.LogError(ex, "根据 ID 查询BOM失败");
        //        throw;
        //    }
        //}



        public async Task<ApiResult<PagingResult<IList<GetBasicInformationDTO>>>> Handle(GetBasicInformationCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有 BOM 和物料数据
                var basicInformations = await _iBasicInformationRepository.GetAllAsync();
                var materials = await _iMaterialRepository.GetAllAsync();

                // 根据 MaterialTypeId 过滤数据
                var filteredData = from basicInformation in basicInformations
                                   join material in materials on basicInformation.MaterialTypeId equals material.MaterialId
                                   where basicInformation.MaterialTypeId == request.MaterialTypeId // 过滤条件
                                   select new GetBasicInformationDTO
                                   {
                                       BomNumber = basicInformation.BomNumber,
                                       BomNumberingState = basicInformation.BomNumberingState,
                                       BomVersionNumber = basicInformation.BomVersionNumber,
                                       BomSpecificationModel = basicInformation.BomSpecificationModel,
                                       BomDefault = basicInformation.BomDefault,
                                       BomDailyOutput = basicInformation.BomDailyOutput,
                                       BomRemark = basicInformation.BomRemark,
                                       BomUsageAmount = basicInformation.BomUsageAmount,
                                       BomRatioMaterialsUsed = basicInformation.BomRatioMaterialsUsed,
                                       BomNameProcessRoute = basicInformation.BomNameProcessRoute,
                                       BomProcessNumber = basicInformation.BomProcessNumber,
                                       BomProcessSpecification = basicInformation.BomProcessSpecification,
                                       UnitName = basicInformation.UnitName,
                                       UnitId = basicInformation.UnitId,
                                       MaterialTypeId = basicInformation.MaterialTypeId,
                                       ProductTypeId = basicInformation.ProductTypeId,
                                   };

                // 分页
                var pagedData = filteredData
                    .Skip(request.PageSize * (request.PageIndex - 1))
                    .Take(request.PageSize)
                    .ToList();

                // 映射到 DTO
                var mappedData = _mapper.Map<IList<GetBasicInformationDTO>>(pagedData);

                // 返回分页结果
                var pagingResult = new PagingResult<IList<GetBasicInformationDTO>>
                {
                    TotalCount = filteredData.Count(),
                    TotalPage = (int)Math.Ceiling(filteredData.Count() / (double)request.PageSize),
                    Data = mappedData
                };

                return ApiResult<PagingResult<IList<GetBasicInformationDTO>>>.Success(pagingResult, StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据 MaterialTypeId 查询分页数据失败，MaterialTypeId: {MaterialTypeId}", request.MaterialTypeId);
                throw;
            }
        }




    }
}
